
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports _2bMatesSite.BO

Namespace _2bMatesSite
	''' <summary>
	''' Summary description for bulletin.
	''' </summary>
	Public Partial Class messages_bulletin
		Inherits BaseWebPage
		Protected chkPostedbul As System.Web.UI.WebControls.CheckBox
		Protected chkPostedbul1 As System.Web.UI.WebControls.CheckBox
		Protected lblSelectall_bulletin As System.Web.UI.WebControls.Label
		Protected lblClearall_bulletin As System.Web.UI.WebControls.Label
		Protected Button1 As System.Web.UI.WebControls.Button
		'protected System.Web.UI.WebControls.HyperLink hlPostBulletin;
		'protected System.Web.UI.HtmlControls.HtmlTableRow trAllFunctions;
		Protected hlGMGroupBlog As System.Web.UI.WebControls.HyperLink
		Protected hlGMGroupTrash As System.Web.UI.WebControls.HyperLink
		Protected grpID As Integer = -1
		Protected grp As Group = Nothing
		Protected usr As User = Nothing
		Protected isGroupMode As Boolean = False
		Protected isModerator As Boolean = False
		Protected htPageConstants As New Hashtable()

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
			' Put user code to initialize the page here
			' this.pageTemplate.PageTitle = PageTitles.BULLETIN_PAGE;

			' Auto login from an external link
			'AutoLogin( Request );			

			'init user
			usr = LoggedUser

			If LoggedUser = Nothing Then
				Common.Utils.RedirectToLoginPage(Page)
			End If

			Dim msgs As ArrayList = Nothing
			Dim MessagesCount As Double = 0

			Me.initPageTitles(Constants.MESSAGES_BULLETIN_PAGE, "", Form1, Nothing, htPageConstants)
			Me.initAdvertisements(Form1, Nothing)

			' init tabs
			grpBlogTabs.ActiveTab = 1
			grpBlogTabs.PageName = Constants.BULLETIN

			' init group
			If Request.Params(Constants.GROUP_PARAM) <> Nothing AndAlso Request.Params(Constants.GROUP_PARAM) <> "" Then
				isGroupMode = True

				If Constants.SHOW_GROUPS <> Constants.SHOW_ON Then
					Throw New Exception(Constants.ERROR_MESSAGE_NO_ACCESS)
				End If

				Try
					grpID = Convert.ToInt32(Request.Params(Constants.GROUP_PARAM))
				Catch
					Throw New Exception(Constants.ERROR_MESSAGE_MISSING_PARAMETERS)
				End Try

				grp = Groups.GetGroupByID(grpID)

				If grp = Nothing Then
					Throw New Exception(Constants.ERROR_MESSAGE_GROUP_DOESNT_EXIST_ERROR)
				End If

				' check if the logged user is a group member
				If Not grp.Members.Contains(usr.ID) Then
					Throw New Exception(Constants.ERROR_MESSAGE_ONLY_MEMBER_CAN_VIEW_MESSAGES)
				End If
			End If

			If isGroupMode Then
				' init page title
				litMainPageTitle.Text = Me.GetPageConstText(htPageConstants, "CONST_GroupTitle_TEXT")

				' init post bulletin link				
				'hlPostBulletin.Text = this.GetPageConstText(htPageConstants, "CONST_PostGroupBulletin_TEXT");

				' Init with group bulletins
				msgs = Messages.GetGroupBulletins(grpID, 0, -1)
				MessagesCount = msgs.Count

				isModerator = (grp.Uid = usr.ID)
				If Not isModerator Then
					btnDelete.Visible = False
					'trAllFunctions.Visible = false;
					dgBulletins.Columns(0).Visible = False
					dgBulletins.Columns(1).Visible = True
				Else
					dgBulletins.Columns(0).Visible = True
					dgBulletins.Columns(1).Visible = False
				End If

				' init menu to group
				grpBlogTabs.Visible = True
				hlConfirmFriends.Visible = True
				hlConfirmFriends.Text = (Me.GetPageConstText(htPageConstants, "CONST_GroupBackLink_TEXT")).Replace("[PARAM]", grp.Name)
				hlConfirmFriends.NavigateUrl = "../" + Constants.GROUP + "?" + Constants.GROUP_PARAM + "=" + grp.ID
			Else
				Response.Redirect(Constants.INBOX)
				' init post bulletin link
				'hlPostBulletin.NavigateUrl = "../" + Constants.POST_BULLETIN;				

				'msgs = Messages.GetUserOutboxBulletins(usr.ID, false);
				msgs = Messages.GetAllUserBulletins(usr.ID, False)
				MessagesCount = msgs.Count

				' init menu to user
				grpBlogTabs.Visible = False

				' init first grid column visibility
				dgBulletins.Columns(0).Visible = True
				dgBulletins.Columns(1).Visible = False

				' init cofirma friends link
				hlConfirmFriends.NavigateUrl = "../" + Constants.VIEW_AWAITING_CONFIRMATION
			End If

			If MessagesCount = 0 Then
				tblMessages.Visible = False
				lblNoMessages.Visible = True
			Else
				If isGroupMode Then
					dgPager.RedirectPage = Constants.BULLETIN + "?" + Constants.GROUP_PARAM + "=" + grp.ID
					dgPagerUp.RedirectPage = Constants.BULLETIN + "?" + Constants.GROUP_PARAM + "=" + grp.ID
				Else
					dgPager.RedirectPage = Constants.BULLETIN
					dgPagerUp.RedirectPage = Constants.BULLETIN
				End If

				dgPager.MaxPageNumber = Convert.ToInt32(Math.Ceiling(MessagesCount / Constants.MAX_MESSAGES_ON_PAGE))
				dgPager.Action = "-1"
				dgPagerUp.MaxPageNumber = Convert.ToInt32(Math.Ceiling(MessagesCount / Constants.MAX_MESSAGES_ON_PAGE))
				dgPagerUp.Action = "-1"

				' initialize listing literals
				dgPager.dgListing.TotalCount = Convert.ToInt32(MessagesCount)
				dgPagerUp.dgListing.TotalCount = Convert.ToInt32(MessagesCount)
				'initialize current page number
				If Convert.ToInt32(Request.Params("page")) = 0 OrElse dgPager.CurrentPageNumber = 1 Then
					dgPager.CurrentPageNumber = 1
					dgPagerUp.CurrentPageNumber = 1
					ViewState("StartIndex") = 0
				Else
					dgPager.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					dgPagerUp.CurrentPageNumber = Convert.ToInt32(Request.Params("page"))
					ViewState("StartIndex") = (dgPager.CurrentPageNumber - 1) * Constants.MAX_MESSAGES_ON_PAGE
				End If

				dgPager.PagesRest = dgPager.MaxPageNumber - dgPager.FirstPageNumber + 1
				dgPager.LastPageNumber = Math.Min(dgPager.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)
				dgPagerUp.PagesRest = dgPagerUp.MaxPageNumber - dgPagerUp.FirstPageNumber + 1
				dgPagerUp.LastPageNumber = Math.Min(dgPagerUp.PagesRest, Constants.MAX_PAGES_NUMS_ON_PAGE)

				If Not IsPostBack Then
					dgBulletins.VirtualItemCount = Convert.ToInt32(MessagesCount)
					BindGrid()
				End If
			End If
		End Sub

		Protected Function CreateDataSource() As ICollection
			Dim msgList As ArrayList
			Dim dt As New DataTable()
			Dim LoggedUsersList As ArrayList = Common.Utils.GetLoggedUsersIDs()

			Dim MessagesCount As Integer = 0

			If isGroupMode Then
				msgList = New ArrayList()
				msgList = Messages.GetGroupBulletins(grpID, 0, -1)
				MessagesCount = msgList.Count
			Else
				' List user's bulletins
				'msgList = Messages.GetUserOutboxBulletins( LoggedUser.ID, false );
				msgList = Messages.GetAllUserBulletins(LoggedUser.ID, False)
				MessagesCount = msgList.Count
			End If

			If MessagesCount <= 0 Then
				dgPager.FirstPageNumber = 1
				dgPager.LastPageNumber = 1
				dgPager.MaxPageNumber = 1
				dgPager.PagesRest = 1
				dgPager.dgListing.StartIndex = 0
				dgPager.dgListing.EndIndex = 0
				dgPagerUp.FirstPageNumber = 1
				dgPagerUp.LastPageNumber = 1
				dgPagerUp.MaxPageNumber = 1
				dgPagerUp.PagesRest = 1
				dgPagerUp.dgListing.StartIndex = 0
				dgPagerUp.dgListing.EndIndex = 0
				dgBulletins.AllowSorting = False
			Else
				dgBulletins.AllowSorting = True
				Dim startIndex As Integer = Convert.ToInt32(ViewState("StartIndex"))
				Dim endIndex As Integer = startIndex + Constants.MAX_MESSAGES_ON_PAGE
				Dim t As Integer = 0
				Dim counter As Integer = 0
				endIndex = Math.Min(endIndex, MessagesCount)
				t = (endIndex - startIndex)
				dgPager.dgListing.StartIndex = startIndex + 1
				dgPager.dgListing.EndIndex = endIndex
				dgPagerUp.dgListing.StartIndex = startIndex + 1
				dgPagerUp.dgListing.EndIndex = endIndex
				Dim curMessageDate As DateTime

				Dim dr As DataRow
				dt.Columns.Add(New DataColumn("MessageID", GetType(Integer)))
				dt.Columns.Add(New DataColumn("Date", GetType(String)))
				dt.Columns.Add(New DataColumn("From", GetType(String)))
				dt.Columns.Add(New DataColumn("URL", GetType(String)))
				dt.Columns.Add(New DataColumn("FriendID", GetType(String)))
				dt.Columns.Add(New DataColumn("SenderName", GetType(String)))
				dt.Columns.Add(New DataColumn("OnlineImg", GetType(String)))
				dt.Columns.Add(New DataColumn("Subject", GetType(String)))
				dt.Columns.Add(New DataColumn("ViewMsgURL", GetType(String)))
				dt.Columns.Add(New DataColumn("MessageIDAndType", GetType(String)))
				dt.Columns.Add(New DataColumn("OnClickJS", GetType(String)))
				dt.Columns.Add(New DataColumn("SenderFullName", GetType(String)))

				If isGroupMode Then
					Dim pic As UserPicture
					' List group's outbox messages
					For Each msg As GroupBulletinMessage In msgList
						If counter >= startIndex AndAlso counter < endIndex Then
							dr = dt.NewRow()
							curMessageDate = msg.DateSent

							dr(0) = msg.ID
							dr(1) = Constants.ARR_MONTHS(curMessageDate.Month - 1) + " " + curMessageDate.Day + "<br />" + curMessageDate.ToShortTimeString()
							pic = msg.Sender.DefaultPicture
							If pic <> Nothing Then
								dr(2) = Pictures.GetPictureSrcFullURL(pic, True, "../")
								

							Else
								dr(2) = Constants.DEFAULT_THUMBNAIL_IMAGE_URL
							End If

							dr(3) = Users.ComposeMemeberLink(msg.Sender)
							dr(10) = Users.ComposeMemeberLinkOnClickJS(msg.Sender, trUserCanceledMessage)

							dr(4) = msg.SenderID.ToString()
							dr(5) = getBeginning(HttpUtility.HtmlEncode(msg.Sender.Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)
							If LoggedUsersList.Contains(msg.SenderID) Then
								dr(6) = "../images/online_status.gif"
							Else
								dr(6) = "../images/spacer.gif"
							End If
							dr(7) = Server.HtmlEncode(msg.Subject)
							dr(8) = "../" + Constants.VIEW_MESSAGE + "?id=" + msg.ID + "&" + Constants.GROUP_PARAM + "=" + grpID
							dr(9) = msg.ID + "-" + msg.MessageType
							dr(11) = msg.Sender.Name
							dt.Rows.Add(dr)
						End If
						System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
					Next
				Else
					Dim pic As UserPicture
					' List user's outbox messages					
					For Each msg As BulletinMessage In msgList
						If counter >= startIndex AndAlso counter < endIndex Then
							dr = dt.NewRow()
							curMessageDate = msg.DateSent

							dr(0) = msg.ID
							dr(1) = Constants.ARR_MONTHS(curMessageDate.Month - 1) + " " + curMessageDate.Day + "<br />" + curMessageDate.ToShortTimeString()
							pic = msg.Sender.DefaultPicture
							If pic <> Nothing Then
								dr(2) = Pictures.GetPictureSrcFullURL(pic, True, "../")
								

							Else
								dr(2) = Constants.DEFAULT_THUMBNAIL_IMAGE_URL
							End If

							dr(3) = Users.ComposeMemeberLink(msg.Sender)
							dr(10) = Users.ComposeMemeberLinkOnClickJS(msg.Sender, trUserCanceledMessage)

							dr(4) = msg.SenderID.ToString()
							dr(5) = getBeginning(HttpUtility.HtmlEncode(msg.Sender.Name), Constants.MAX_NAME_LENGTH_ABOVE_IMAGE)
							If LoggedUsersList.Contains(msg.SenderID) Then
								dr(6) = "../images/online_status.gif"
							Else
								dr(6) = "../images/spacer.gif"
							End If
							dr(7) = Server.HtmlEncode(msg.Subject)
							dr(8) = "../" + Constants.VIEW_MESSAGE + "?id=" + msg.ID
							dr(9) = msg.ID + "-" + msg.MessageType
							dr(11) = msg.Sender.Name
							dt.Rows.Add(dr)
						End If
						System.Math.Max(System.Threading.Interlocked.Increment(counter),counter - 1)
					Next
				End If
			End If

			Dim dv As New DataView(dt)
			Return dv
		End Function

		Protected Sub BindGrid()
			'init datagrid with database data ordered by "orederBy" param
			dgBulletins.DataSource = CreateDataSource()
			dgBulletins.DataBind()
			SetStyle()
		End Sub


		#region Web Form Designer generated code
		Protected Overloads Overrides Sub OnInit(ByVal e As EventArgs)
			'
			' CODEGEN: This call is required by the ASP.NET Web Form Designer.
			'
			InitializeComponent()
			MyBase.OnInit(e)
		End Sub

		''' <summary>
		''' Required method for Designer support - do not modify
		''' the contents of this method with the code editor.
		''' </summary>
		Private Sub InitializeComponent()
			AddHandler Me.dgBulletins.ItemCommand, AddressOf Me.dgBulletins_ItemCommand
		End Sub
#End Region

		Private Sub dgBulletins_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)
			Dim cmd As String = e.CommandName

			If cmd.Equals("MemberRedirect") Then
				Response.Redirect(Constants.MEMBERS + "?id=" + e.CommandArgument)
			End If
		End Sub

		Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			Dim cbCheckedValue As String
			Dim cb As CheckBox
			Dim idandtype As String()
			Dim MessageID As Integer
			Dim MessageType As String

			For Each dgi As DataGridItem In Me.dgBulletins.Items
				cb = DirectCast(dgi.Cells(0).Controls(1), CheckBox)
				cbCheckedValue = Request.Params(dgi.Cells(0).Controls(1).UniqueID)

				If cbCheckedValue <> Nothing AndAlso cbCheckedValue.Equals("on") Then
					idandtype = cb.Attributes("value").Split("-"C)
					MessageID = Convert.ToInt32(idandtype(0))
					MessageType = idandtype(1)
					If isGroupMode Then
						' Move group bulletins to trash
						If MessageType = "mtGroupBulletin" Then
							Dim bulMsg As GroupBulletinMessage = Messages.GetGroupBulletin(grpID, MessageID)
							bulMsg.IsMarkedDeleted = True
							bulMsg.Save()
						End If
					Else
						If MessageType = "mtBulletin" Then
							Dim bulMsg As BulletinMessage = Messages.GetUserBulletin(LoggedUser.ID, MessageID, False)
							bulMsg.IsMarkedDeleted = True
							bulMsg.Save()
						End If
					End If
				End If
			Next
			dgBulletins.DataBind()
			If isGroupMode Then
				Response.Redirect(Constants.BULLETIN + "?" + Constants.GROUP_PARAM + "=" + grp.ID)
			Else
				Response.Redirect(Constants.BULLETIN)
			End If
		End Sub

		Private Sub SetStyle()
			Dim cb As CheckBox
			Dim msg As BulletinMessage
			Dim isRead As Boolean
			Dim idandtype As String()
			Dim MessageID As Integer
			Dim MessageType As String

			For Each dgi As DataGridItem In Me.dgBulletins.Items
				cb = DirectCast(dgi.Cells(0).Controls(1), CheckBox)
				idandtype = cb.Attributes("value").Split("-"C)
				MessageID = Convert.ToInt32(idandtype(0))
				MessageType = idandtype(1)
				isRead = False

				If isGroupMode Then
					msg = Messages.GetGroupBulletin(grpID, MessageID)
					isRead = msg.IsRead
				Else
					msg = Messages.GetUserBulletin(LoggedUser.ID, MessageID, False)
					isRead = msg.IsRead
				End If

				If isRead Then
					dgi.CssClass = Constants.READ_MESSAGE_STYLE
				Else
					dgi.CssClass = Constants.UNREAD_MESSAGE_STYLE
				End If
			Next
		End Sub

	End Class
End Namespace






